package com.ytrsoft.task;

import com.ytrsoft.bean.Message;
import com.ytrsoft.utils.CodeKit;
import com.ytrsoft.utils.MsgKit;
import com.ytrsoft.ws.BaseSocket;
import org.codehaus.janino.SimpleCompiler;

public class RunHandler extends ExecutorHandler implements ActionHandler {

    private final BaseSocket socket;

    public RunHandler(BaseSocket socket) {
        this.socket = socket;
    }

    @Override
    public void doMessage(Message msg) {
        start(msg);
    }

    @Override
    protected void running(Message msg) {
        String javaCode = msg.getBody();
        String className = CodeKit.findClassName(javaCode);
        if (className == null) {
            Message error = MsgKit.create("无法找到类名");
            socket.postMessage(error);
            return;
        }
        SimpleCompiler compiler = new SimpleCompiler();
        try {
            compiler.cook(javaCode);
            Class<?> cls = compiler.getClassLoader().loadClass(className);
            CodeKit.invokeMain(cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        killNow();
    }

}
